from syl import settings
from django.core.paginator import InvalidPage, Paginator
from haystack.forms import ModelSearchForm
from django.http import JsonResponse

RESULTS_PER_PAGE = getattr(settings, 'HAYSTACK_SEARCH_RESULTS_PER_PAGE', 15)


# 搜索接口
def course_index_search(request):
    query = request.GET.get('q', None)
    page = int(request.GET.get('page', 1))
    page_size = int(request.GET.get('page_size', RESULTS_PER_PAGE))
    if query:
        form = ModelSearchForm(request.GET, load_all=True)
        if form.is_valid():
            results = form.search()
        else:
            results = []
    else:
        return JsonResponse({"code": 404, "msg": 'No file found！', "data": []})

    paginator = Paginator(results, page_size)
    try:
        page = paginator.page(page)
    except InvalidPage:
        return JsonResponse({"code": 404, "msg": 'No file found！', "data": []})

    jsondata = []
    for result in page.object_list:
        data = {
            'id': result.object.id,
            'title': result.object.title,
            'desc': result.object.desc,
            'img': request.scheme + '://' + request.META['HTTP_HOST'] + result.object.img.url,
            'follower': result.object.follower,
            'learner': result.object.learner,
            'status': result.object.status,
            'course_type': result.object.course_type.id
        }
        jsondata.append(data)
    result = {
        "code": 200,
        "msg": 'Search successfully！',
        "data": {"count": page.paginator.count, "results": jsondata}
    }
    return JsonResponse(result)
